import component from './alert.vue';

let alertQueue = [], currentAlert;

function getType (str) {
    return Object.prototype.toString.call(str).split(' ')[1].split(']')[0];
}

function showNextMsg() {
    if (!Vue.prototype.$rxAlert.show) {
        if (alertQueue.length > 0) {
            currentAlert = alertQueue.shift();
            let opt = currentAlert.opt;
            Vue.prototype.$rxAlert.show = true;
            Vue.prototype.$rxMask(component, opt).then(res => {
                Vue.nextTick(() => {
                    showNextMsg();
                    currentAlert.reslove(res);
                })
            });
        }
    }
}

function mesBox (opt) {
    return new Promise((resolve, reject) => {
        alertQueue.push({
            opt: opt,
            reslove: resolve,
            reject: reject
        });
        showNextMsg();
    });
}

function Alert (title, options) {
    let titleType = getType(title);
    options = options || {};
    if (titleType == 'Object') {
        options.title = title;
    } else {
        options = {
            title: title,
            btns: options.btns || '确定'
        }
    }
    return mesBox(options);
}

function Confirm (title, message, options) {
    let messageType = getType(message);
    options = options || {};
    options.title = title;
    if (messageType == 'Object') {
        options = message;
    } else {
        options = {
            title: title,
            text: message,
            btns: options.btns
        }
    }
    return mesBox(options);
}

function Msgbox(options) {
    let optionsType = getType(options);
    if (optionsType != 'Object') {
        options = {
            title: options
        }
    }
    options.btns =  options.btns || '确定';
    return mesBox(options);
}

export {
    Alert,
    Confirm,
    Msgbox
};